package models

import (
	"fmt"
	"gitee.com/sansaniot/ssiot-core/httpmvc/model"
	"gorm.io/gorm"
	cDto "ssdevice/common/dto"
	"ssdevice/common/utils"
	"ssdevice/internal/device/models/query"
	"strings"
	"time"
)

type SysOperate struct {
	Id          string          `json:"id" gorm:"primaryKey;type:varchar(64);comment:ID"`
	Username    string          `json:"username" gorm:"type:varchar(64);comment:用户名"`
	OperateType string          `json:"operateType" gorm:"type:varchar(64);comment:操作类型"`
	Content     string          `json:"content" gorm:"type:text;comment:操作内容"`
	DevSn       string          `json:"devSn" gorm:"type:varchar(64);comment:设备SN"`
	CreateTime  *cDto.LocalTime `json:"createTime" gorm:"type:timestamptz(6);comment:创建时间"`
	model.Model
}

// 构建操作内容
func (e *SysOperate) BuildContent(data map[string]interface{}) string {
	var content strings.Builder
	for k, v := range data {
		content.WriteString(fmt.Sprintf("%s -> %v", k, v))
	}
	return content.String()
}

// 添加操作记录
func (e *SysOperate) AddRecord(username, operateType string, devSn string, data map[string]interface{}) error {
	e.Id = utils.SimpleUUID()
	e.Username = username
	e.OperateType = operateType
	e.Content = e.BuildContent(data)
	e.DevSn = devSn
	now := cDto.LocalTime(time.Now())
	e.CreateTime = &now
	return e.Add()
}

func (e *SysOperate) Add() error {
	return e.Orm.Create(e).Error
}

func (e *SysOperate) FindOperateList(req *query.SysOperateQuery) (err error, result []*SysOperate, total int64) {
	// 初始化查询
	var where func(db *gorm.DB) *gorm.DB

	if req.DevSn == "" {
		where = func(db *gorm.DB) *gorm.DB {
			return db.Where("username = ?", req.Username)
		}
	} else {
		where = func(db *gorm.DB) *gorm.DB {
			return db.Where("username = ? and dev_sn = ?", req.Username, req.DevSn)
		}
	}

	err = e.Orm.Model(e).Scopes(
		where,
		cDto.OrderDest("create_time", true, req.OrderBy),
		cDto.Paginate(req.GetPageSize(), req.GetPageIndex()),
	).Find(&result).Limit(-1).Offset(-1).Count(&total).Error

	return
}

func (e *SysOperate) TableName() string {
	return "sys_dev_operate_log"
}
